package com.foreknow.sevlet;

import com.foreknow.model.User;
import com.foreknow.service.impl.UserServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet({"/user/ree","/user/login1"})
public class UserServlet extends HttpServlet {
    private UserServiceImpl service;
    public UserServlet(){
        service=new UserServiceImpl();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String uri=request.getRequestURI();
        Map<String,Object> data=new HashMap<>();
        Gson gson=new Gson();
        if (uri.endsWith("/user/login1")){
            String username=request.getParameter("username");
            String password=request.getParameter("password");
            User user = service.Login(username, password);
            if (user!=null){
                data.put("error",0);
                data.put("message","登录成功");
                user.setPassword("");
                data.put("user",user);
            }else {
                data.put("error",1);
                data.put("message","登录失败");
                data.put("user",null);
            }
        }else if (uri.endsWith("/user/ree")){
            String username=request.getParameter("username");
            String account=request.getParameter("account");
            String password=request.getParameter("password");
            String phone = request.getParameter("phone");
            String email = request.getParameter("email");
            String avatar = request.getParameter("avatar");
            User[] users=new User[1];
            User user=new User( username,  account,  password,  phone,  email,  avatar);
            users[0]=user;
            if (service.Registered(users)){
                data.put("error",0);
                data.put("message","注册成功");
                user.setPassword("");
                data.put("user",user);
            }else {
                data.put("error",-1);
                data.put("mesage","注册失败");
                data.put("user",null);
            }
        }
        String json=gson.toJson(data);
        response.getWriter().write(json);
        data.clear();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
